package org.example.c4;

import lombok.extern.slf4j.Slf4j;

/**
 * 算法：统计给定的数二进制位最高位为１前面0的个数
 */
@Slf4j
public class Demo4 {
    public static void main(String[] args) {
        log.info("{}", numberOfLeadingZeros(2));
        log.info("{}", numberOfLeadingZeros(4));
    }

    //来自Integer.numberOfLeadingZeros方法
    public static int numberOfLeadingZeros(int i) {
        // HD, Figure 5-6
        if (i == 0)
            return 32;
        int n = 1;
        if (i >>> 16 == 0) {
            n += 16;
            i <<= 16;
            log.info("16 -> {} {}", n, i);
        }
        if (i >>> 24 == 0) {
            n += 8;
            i <<= 8;
            log.info("24 -> {} {}", n, i);
        }
        if (i >>> 28 == 0) {
            n += 4;
            i <<= 4;
            log.info("28 -> {} {}", n, i);
        }
        if (i >>> 30 == 0) {
            n += 2;
            i <<= 2;
            log.info("30 -> {} {}", n, i);
        }
        n -= i >>> 31;
        log.info("final {} {}", n, i);
        return n;
    }
}